// nodejs的require模块实现过程
//1. 先识别路径  找到文件
//2. 进行后缀补全  .js =>.json=> .node
//3. 读取文件内容 编译返回
const fs = require("fs");
const path = require("path");
const vm = require("vm");

function myModule(id) {
  this.id = id;
  this.exports = {};
}

myModule.cache = {};
myModule.wrapper = [
  "(function(exports,require,module,__filename,__dirname){",
  "})",
];
myModule.extname = {
  ".js"(module) {
    let content = fs.readFileSync(module.id, "utf8");
    content = myModule.wrapper[0] + content + myModule.wrapper[1];
    const compileFn = vm.runInThisContext(content);
    const exports = module.exports;
    const __filename = module.id;
    const __dirname = path.dirname(module.id);
    compileFn.call(exports, exports, MyRequire, module, __filename, __dirname);
  },
  ".json"(module) {
    let content = fs.readFileSync(module.id, "utf8");
    content = JSON.parse(content);
    module.exports = content;
  },
};

myModule._resolveFilename = function (filePath) {
  let absPath = path.resolve(__dirname, filePath);
  if (fs.existsSync(absPath)) {
    return absPath;
  } else {
    const extname = Object.keys(myModule.extname);
    for (const value of extname) {
      let newPath = absPath + value;
      if (fs.existsSync(newPath)) {
        return newPath;
      }
    }
    return new Error("文件不存在");
  }
};

myModule.prototype.load = function () {
  const extname = path.extname(this.id);
  myModule.extname[extname](this);
};
function MyRequire(filePath) {
  let myPath = myModule._resolveFilename(filePath);
  const myCache = myModule.cache[myPath];
  if (myCache) return myCache.exports;
  let module = new myModule(myPath);
  console.log(module);

  myModule.cache[myPath] = module;
  module.load();
  return module.exports;
}
const obj = MyRequire("./03.case");

console.log(obj, "ss");
